package com.jt.SecurityMain;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.service.UserService;
import org.boon.primitive.Arry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 实现UserDetailsService接口，@Configuration将LoginUserDetailsService注入到容器中去，将UserDetails返回,
 * 自定义登录用户，不用默认的 user
 */
@Configuration
public class LoginUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*查询用户信息*/
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName, username));
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码不存在");
        }
        /*获取到权限集合和用户信息传入UserDetails中去*/
         Map<String, Object> map = userService.selectMenuList(user.getId());
        List<String> list =  ( List<String>) map.get("permissionList");
        LoginUser loginUser = new LoginUser(user, list);
        /*查询权限信息*/
        return loginUser;
    }
}
